<?   /*
  // File       :   exim4.wcp.phps
  // Purpose    :   Manage virtual mail domains with exim4
  // Author    :   bowlby, contact me at bowlby [ at ] dds.nl
  // Comment    :   First setup Exim4 with virtual domains see for example:
       //             see for example:  http://koivi.com/exim4-config/
                for the autoreply part to work:
add a file named '850_exim4-config_vacation' to the exim4-router-dir with the following contents:
//////////////////////////
user_vacation:
     driver = accept
     check_local_user
     # do not reply to errors or lists
     condition = "${if or {{match {$h_precedence:} {(?i)junk|bulk|list}} {eq {$sender_address} {}}} {no} {yes}}"
     no_expn
     require_files = $home/vacation.msg
     # do not reply to errors and bounces or lists
     senders = " ! ^.*-request@.*:\
                 ! ^owner-.*@.*:\
                 ! ^postmaster@.*:\
                 ! ^listmaster@.*:\
                 ! ^mailer-daemon@.*\
                 ! ^root@.*"
     transport = vacation_reply
     unseen
     user = ${local_part}
     no_verify
////////////////////////
add a file named '30_exim4-config_vacation' to the exim4-transport-dir with the following contents:
//////////////////////////////
vacation_reply:
     driver = autoreply
     file = $home/vacation.msg
     file_expand
     from = Autoreply System <$original_local_part@$original_domain>
     log = $home/vacation.log
     once = $home/vacation.db
     once_repeat = 7d
     subject = ${if def:h_Subject: {Re: ${quote:${escape:${length_50:$h_Subject:}}} (autoreply)} {I am on vacation} }
     text = "\
     Dear $h_from\n\n\
     This is an automatic reply.  Feel free to send additional\n\
     mail, as only this one notice will be generated.  The following\n\
     is a prerecorded message, sent for $original_local_part@$original_domain:\n\
     ====================================================\n\n\
     "
     to = "$sender_address"
////////////////////////////////
*/
// Handle email domain manipulation
if ($type == "domain") {
    // Create Domain :: expect *
	if ($data['action'] == "create"){
  
		// First check to see if it's a pointer, and if it is, set it up here.
                $dbp = mysql_query("SELECT DISTINCT host, domain, sub, sdmail FROM domains WHERE id='".$data['owner']."'");
                $ddata = mysql_fetch_array($dbp);
                if ( $data['type'] == 'pointer' ){
                        symlink ("/etc/mail/virtual/" . $ddata['domain'],  "/etc/mail/virtual/" . $data['domain']);

                }elseif ( $data['type'] == 'domain'){
                        if($data['sub']=='true' && ($data['sdmail'] == 'true' || $data['sdmail']=='both') && !file_exists("/etc/mail/virtual/".$ddata['host'].".".$data['domain'])){
                                $sysfile[ 'aliases'] = file_get_contents($cfg['basedir']."/headers/aliases");
                                $file=fopen("/etc/mail/virtual/".$data['hostname'].".".$data['domain'], "w");
                                fputs($file, $sysfile['aliases']);
                                fclose($file);
                        }
                        if($data['sub']=='true' && ($data['sdmail'] == 'false' || $data['sdmail']=='both')  && !file_exists("/etc/mail/virtual/".$data['domain'])){
                                $sysfile[ 'aliases'] = file_get_contents($cfg['basedir']."/headers/aliases");
                                $file=fopen("/etc/mail/virtual/".$data['domain'], "w");
                                fputs($file, $sysfile['aliases']);
                                fclose($file);
                        }elseif(!file_exists("/etc/mail/virtual/".$data['domain'])){
                                $sysfile[ 'aliases'] = file_get_contents($cfg['basedir']."/headers/aliases");
                                $file=fopen("/etc/mail/virtual/".$data['domain'], "w");
                                fputs($file, $sysfile['aliases']);
                                fclose($file);
                        }

                }
     
     
        // Update Domain :: expect *
	if ($data['action'] == "update"){
       
		// Check to see if we're updating a domain, and if so do it.
		if ( $data['type'] == 'domain' ){
			if ($data['domain'] != $data['domain1']){
         
				rename("/etc/mail/virtual/".$data['domain1'], "/etc/mail/virtual/".$data['domain']);
        	}
        }
		
		elseif ( $data['type'] == 'pointer' ){
			if ($data['domain'] != $data['domain1']){
                
                rename("/etc/mail/virtual/" .$data['domain1'], "/etc/mail/virtual/" .$data['domain']);
			}
        }
	}
	
	// Remove Domain :: expect username
	if ($data['action'] == "remove") {
		// Delete domain first then check for pointers and if they exist delete them.
		// solution: by deleting the domain-alias-file we should be in the clear and
		// after we've found the pointers they'll be deleted
		
		//if($data['type'] == 'domain' ){
		//	unlink("/etc/mail/virtual/".$data['domain']);
		//}
			
		elseif($data['type'] == 'pointer' ){
     		unlink("/etc/mail/virtual/".$data['domain']);
		}
    }
}

// Handle User Manipulation
if ($type == "user") {
	
	// Get domain name
	$dbp = mysql_query("SELECT DISTINCT host, domain, domain1, sub, sdmail FROM domains WHERE id='".$data['id']."'");
	$ddata = mysql_fetch_array($dbp);
	
	$autoreplydir = $cfg['basedir'].'/autoresponder/';
	
        if($ddata['sdmail'] == "false" || $ddata['sdmail'] == "both"){
            $adq=mysql_query("select id from domains where domain='".$ddata['domain']."' and (sdmail='false' or sdmail='both')");
            $firstrun=true;
            while($addata=mysql_fetch_array($adq)){

                $all = mysql_query("SELECT username, root, aliases, forward FROM users WHERE action != 'remove' AND forward='' AND id= '".$addata['id']."'");
                $user = mysql_query("SELECT username, root, aliases, forward FROM users WHERE action != 'remove' AND forward='' AND id= '".$addata['id']."'");
                $autoreply = mysql_query("SELECT username, root, autoreply FROM users WHERE action != 'remove' AND autoreply!='' AND id= '".$addata['id']."'");
                $catch = mysql_query("SELECT username FROM users WHERE action != 'remove' AND catchall='true' AND id= '".$addata['id']."'");
                $forward = mysql_query("SELECT username, root, aliases, forward FROM users WHERE action != 'remove' AND forward!='' AND id = '".$addata['id']."'");

                //clean up all forward and vacation files
                while($row1=mysql_fetch_array($all)){
                    if(file_exists($row1['root']."/forward-addresses")) unlink($row1['root']."/forward-addresses");
                    if(file_exists($row1['root']."/vacation.msg")) unlink($row1['root']."/vacation.msg");
                    if(file_exists($row1['root']."/vacation.db")) unlink($row1['root']."/vacation.db");
                    if(file_exists($row1['root']."/vacation.log")) unlink($row1['root']."/vacation.log");
                }

                //create vacation.msg in user-home
                while($row3=mysql_fetch_array($autoreply)){
                    $vac=fopen($row3['root']."/vacation.msg","w");
                    fputs($vac,$row3['autoreply']);
                    fclose($vac);
                    chown($row3['root']."/forward-addresses", $row3['username']);
                    chgrp($row3['root']."/forward-addresses", "g".$addata['id']);
                }
        
                if($firstrun){
                    $dir ="/etc/mail/virtual/";
                    $dfile= $dir.$ddata['domain'];
                    $domaliasfile = fopen($dfile,"w");
    
                    //Start making the domain-alias-file
                    
                    //put header in domain-alias-file
                    $header = file_get_contents($cfg['basedir'].'/headers/aliases');
                    fputs($domaliasfile, $header);
	
                    //put catchall-address in (if exists)
                    $catchall = mysql_fetch_array($catch);
	
                    if($catchall['username']!=""){
            		fputs($domaliasfile,"\n\n######  Catch-all #####\n");
			fputs($domaliasfile,"*: :include:".$catchall['root']."/forward-addresses ,".$catchall['username']."@localhost\n");
			fputs($domaliasfile,"#######################\n\n");
                    }
                    if($catchall['username']==""){
                        fputs($domaliasfile,"\n\n######  no Catch-all, unknown addresses will be bounced#####\n");
                        fputs($domaliasfile,"*: :fail: The address doesn't exist");
                        fputs($domaliasfile,"##############################################################\n\n");
                    }
                }
                $firstrun=false;

                //put in usernames and aliasses (from users without forward-addresses)
		while($row =mysql_fetch_array($user, MYSQL_ASSOC)){
                        $unixname=get_property('unix user', $addata['id'], $row['username']);
                        fputs($domaliasfile, $row['username'].": ".$unixname."@localhost\n");
                        $alias=explode(" " , $row['aliases']);
                                foreach($alias as $key=>$value){
                                        if($value!="") fputs($domaliasfile, $value.": ".$row['username']."\n");
                                }
                }

                //put in usernames and aliasses (from users with forward-addresses)
                while($row2 =mysql_fetch_array($forward, MYSQL_ASSOC)){
                        $unixname=get_property('unix user', $addata['id'], $row2['username']);
                        fputs($domaliasfile, $row2['username'].": ".$unixname."@localhost, :include:".$row2['root']."/forward-addresses\n");
                        $alias=explode(" " , $row2['aliases']);
                                foreach($alias as $key=>$value){
                                        if($value!="") fputs($domaliasfile, $value.": ".$row2['username']."\n");
                                }
                }

                //create forward-addresses files in user-homes    
		$ffile=fopen($row2['root']."/forward-addresses","w");
           	$fheader = file_get_contents($cfg['basedir'].'/headers/forward-addresses');
	        fputs($ffile,$fheader);
		$forward2=explode(" ",$row2['forward']);
            
		foreach($forward2 as $key=>$value){
                    if($value!="") fputs($ffile, "\n".$value);
		}
                fclose($ffile);
                chown($row2['root']."/forward-addresses", $row2['username']);
                chgrp($row2['root']."/forward-addresses", "g".$addata['id']);
            }
            fclose($domaliasfile);
        }
        if($ddata['sdmail'] == "true" || $ddata['sdmail'] == "both"){

            $all = mysql_query("SELECT username, root, aliases, forward FROM users WHERE action != 'remove' AND forward='' AND id= '".$data['id']."'");
            $user = mysql_query("SELECT username, root, aliases, forward FROM users WHERE action != 'remove' AND forward='' AND id= '".$data['id']."'");
            $autoreply = mysql_query("SELECT username, root, autoreply FROM users WHERE action != 'remove' AND autoreply!='' AND id= '".$data['id']."'");
            $catch = mysql_query("SELECT username FROM users WHERE action != 'remove' AND catchall='true' AND id= '".$data['id']."'");
            $forward = mysql_query("SELECT username, root, aliases, forward FROM users WHERE action != 'remove' AND forward!='' AND id = '".$data['id']."'");

            //clean up all forward and vacation files
            while($row1=mysql_fetch_array($all)){
                if(file_exists($row1['root']."/forward-addresses")) unlink($row1['root']."/forward-addresses");
                if(file_exists($row1['root']."/vacation.msg")) unlink($row1['root']."/vacation.msg");
                if(file_exists($row1['root']."/vacation.db")) unlink($row1['root']."/vacation.db");
                if(file_exists($row1['root']."/vacation.log")) unlink($row1['root']."/vacation.log");
            }

            //create vacation.msg in user-home
            while($row3=mysql_fetch_array($autoreply)){
                $vac=fopen($row3['root']."/vacation.msg","w");
                fputs($vac,$row3['autoreply']);
                fclose($vac);
                chown($row3['root']."/forward-addresses", $row3['username']);
                chgrp($row3['root']."/forward-addresses", "g".$data['id']);
            }

            $dir ="/etc/mail/virtual/";
            $dfile= $dir.$ddata['host'].".".$ddata['domain'];
            $domaliasfile = fopen($dfile,"w");

            //Start making the domain-alias-file

            //put header in domain-alias-file
            $header = file_get_contents($cfg['basedir'].'/headers/aliases');
            fputs($domaliasfile, $header);

            //put catchall-address in (if exists)
            $catchall = mysql_fetch_array($catch);

            if($catchall['username']!=""){
                fputs($domaliasfile,"\n\n######  Catch-all #####\n");
                fputs($domaliasfile,"*: :include:".$catchall['root']."/forward-addresses ,".$catchall['username']."@localhost\n");
                fputs($domaliasfile,"#######################\n\n");
            }
            if($catchall['username']==""){
                fputs($domaliasfile,"\n\n######  no Catch-all, unknown addresses will be bounced#####\n");
                fputs($domaliasfile,"*: :fail: The address doesn't exist");
                fputs($domaliasfile,"##############################################################\n\n");
            }

            //put in usernames and aliasses (from users without forward-addresses)
            while($row =mysql_fetch_array($user, MYSQL_ASSOC)){
                    $unixname=get_property('unix user', $data['id'], $row['username']);
                    fputs($domaliasfile, $row['username'].": ".$unixname."@localhost\n");
                    $alias=explode(" " , $row['aliases']);
                            foreach($alias as $key=>$value){
                                    if($value!="") fputs($domaliasfile, $value.": ".$row['username']."\n");
                            }
            }

            //put in usernames and aliasses (from users with forward-addresses)
            while($row2 =mysql_fetch_array($forward, MYSQL_ASSOC)){
                    $unixname=get_property('unix user', $data['id'], $row2['username']);
                    fputs($domaliasfile, $row2['username'].": ".$unixname."@localhost, :include:".$row2['root']."/forward-addresses\n");
                    $alias=explode(" " , $row2['aliases']);
                            foreach($alias as $key=>$value){
                                    if($value!="") fputs($domaliasfile, $value.": ".$row2['username']."\n");
                            }
            }

            //create forward-addresses files in user-homes    
            $ffile=fopen($row2['root']."/forward-addresses","w");
            $fheader = file_get_contents($cfg['basedir'].'/headers/forward-addresses');
            fputs($ffile,$fheader);
            $forward2=explode(" ",$row2['forward']);

            foreach($forward2 as $key=>$value){
                if($value!="") fputs($ffile, "\n".$value);
            }
            fclose($ffile);
            chown($row2['root']."/forward-addresses", $row2['username']);
            chgrp($row2['root']."/forward-addresses", "g".$addata['id']);
            fclose($domaliasfile);
        }
 }
?>
